package user

import (
	"encoding/json"

	"gitee.com/xgotool/backend-framework-template/config"
	"gitee.com/xgotool/backend-framework-template/model"
	"gitee.com/xiaoyutab/xgotool/individual/xginplus"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 后台角色列表信息
//
//	GET	/user/role_list
func RoleList(c *xginplus.Context) *xginplus.Response {
	type temp_struct struct {
		RoleName  string      `json:"role_name" form:"role_name" xml:"role_name"`    // 搜索关键词
		Status    json.Number `json:"status" form:"status" xml:"status"`             // 状态 -1-禁用 1-启用 0-全部
		BeginTime json.Number `json:"begin_time" form:"begin_time" xml:"begin_time"` // 开始时间
		EndTime   json.Number `json:"end_time" form:"end_time" xml:"end_time"`       // 结束时间
	}
	temp := temp_struct{}
	if err := c.Bind(&temp); err != nil {
		return c.Error(err)
	}
	type temp_struct_used struct {
		RoleName  string // 搜索关键词
		Status    int    // 状态 -1-禁用 1-启用 0-全部
		BeginTime int64  // 开始时间
		EndTime   int64  // 结束时间
	}
	param := temp_struct_used{}
	// 参数赋值
	param.RoleName = temp.RoleName
	param.Status = xstring.JInt(temp.Status)
	param.BeginTime = xstring.JInt64(temp.BeginTime)
	param.EndTime = xstring.JInt64(temp.EndTime)
	// ApiPost软件所需要的参数描述格式:
	// [{"is_checked":1,"not_null":-1,"key":"role_name","type":"Text","field_type":"String","value":"","description":"搜索关键词"},{"is_checked":1,"not_null":-1,"key":"status","type":"Text","field_type":"Integer","value":"","description":"状态 -1-禁用 1-启用 0-全部"},{"is_checked":1,"not_null":-1,"key":"begin_time","type":"Text","field_type":"Integer","value":"","description":"开始时间"},{"is_checked":1,"not_null":-1,"key":"end_time","type":"Text","field_type":"Integer","value":"","description":"结束时间"}]
	// ApiFox软件所需要的参数描述格式:（此软件需要的参数为多行形式，请手动去除最前面的//和空格，再行复制）
	// "role_name","string","false","","","搜索关键词"
	// "status","integer","false","","","状态 -1-禁用 1-启用 0-全部"
	// "begin_time","integer","false","","","开始时间"
	// "end_time","integer","false","","","结束时间"
	// 其他软件所需要的KV键值对描述:
	// {"role_name":"搜索关键词","status":"状态 -1-禁用 1-启用 0-全部","begin_time":"开始时间","end_time":"结束时间"}
	// 本命令执行参数【留做备份，以便后期使用/修改】
	// role_name string 搜索关键词 status int 状态 -1-禁用 1-启用 0-全部 begin_time int64 开始时间 end_time int64 结束时间 x.ginplus
	// 参数效验部分

	conn, err := config.GetConnect()
	if err != nil {
		return c.Error(err)
	}
	var count int64
	mod, mods := model.Role{}, []model.Role{}
	conn.Table(mod.TableName()).
		Where("is_deleted", 0).
		When(param.Status == 1, "status", 1).
		When(param.Status == -1, "status", 0).
		WhenLike(param.RoleName != "", []string{"role_name", "remark"}, param.RoleName).
		When(param.BeginTime > 0, "created_at >= ?", param.BeginTime).
		When(param.EndTime > 0, "created_at <= ?", param.EndTime).
		List(c.GetInt("offset"), c.GetInt("limit"), &count, &mods)
	for i := 0; i < len(mods); i++ {
		json.Unmarshal([]byte(mods[i].RoleMenu), &mods[i].MenuIds)
	}
	return c.SuccessPage(count, mods)
}
